﻿using Dapper;
using Entity;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Data.SqlClient;
using Realize;
using System.Data;
using System.Reflection;
using System.Threading.Tasks;

namespace WebApplication9.Controllers.ClientSet
{
    public class SJJGSZController : Controller
    {
        private readonly IConfiguration configuration;

        public SJJGSZController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Index2(int pageSize,int currentPage)
        {
            //CFTK cFTK = new CFTK();
            //List<Config_File_Third_Kind> zhi = await cFTK.SelectCFTKAsync(configuration["SqlServer"]);
            //return Ok(new
            //{
            //    list = zhi
            //});
            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "ftk_id");
                param.Add("@tableName", "config_file_third_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Config_File_Third_Kind> list = conn.Query<Config_File_Third_Kind>(sql, param).ToList();

                FenYe<Config_File_Third_Kind> fenYecs = new FenYe<Config_File_Third_Kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("totalRows");
                //return fenYecs;
                return Json(fenYecs);

            }
        }

        public async Task<IActionResult> AddCFTK()
        {
            ICFFK cFFK = new CFFK();
            List<Config_File_First_Kind> cfk = await cFFK.SelectCFFKAsync(configuration["SqlServer"]);
            SelectList selectListItems = new SelectList(cfk, "first_kind_name", "first_kind_name");
            ViewBag.D = selectListItems;

            //CFSK cFsK = new CFSK();
            //List<Config_File_Second_Kind> cfk1 = await cFsK.SelectCFSKAsync(configuration["SqlServer"]);
            //SelectList selectListItems1 = new SelectList(cfk1, "second_kind_name", "second_kind_name");
            //ViewBag.H = selectListItems1;

            ICFTK cFTK = new CFTK();
            List<Config_File_Third_Kind> cfk2 = await cFTK.SelectCFTKAsync(configuration["SqlServer"]);
            SelectList selectListItems2 = new SelectList(cfk2, "third_kind_is_retail", "third_kind_is_retail");
            ViewBag.F = selectListItems2;

            return View();
        }



        [HttpGet]
        public async Task<IActionResult> GetSecondKinds(string firstKindName)
        {
            if (string.IsNullOrEmpty(firstKindName))
                return BadRequest("请选择一级机构");

            ICFSK cFsK = new CFSK();
            var secondKinds = await cFsK.SelectCFSKLBAsync(configuration["SqlServer"], firstKindName);

            // 转换为SelectListItem集合
            var selectList = secondKinds.Select(sk => new SelectListItem
            {
                Value =sk.second_kind_name,
                Text = sk.second_kind_name
            }).ToList();

            return Ok(selectList);
        }




        [HttpPost]
        public async Task<IActionResult> AddCFTK(Config_File_Third_Kind cftk )
        {
           
            //操作
            ICFTK cFTK = new CFTK();
            int js = await cFTK.AddCFTKAsync(cftk, configuration["SqlServer"]);
            if (js > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }

        public async Task<IActionResult> Update(int id)
        {
            ICFTK cFTK = new CFTK();
            ViewData.Model = await cFTK.SelectCFTKIDAsync(id, configuration["SqlServer"]);
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Update(Config_File_Third_Kind cftk,int id)
        {
            //根据参数做修改操作
            ICFTK cFTK = new CFTK();
            int result = await cFTK.UpdateCFTKAsync(cftk, configuration["SqlServer"], id);
            if (result > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();

            }
        }

        public async Task<IActionResult> Delete(int id)
        {

            ICFTK cFTK = new CFTK();
            int zhi = await cFTK.DeleteCFTKAsync(id, configuration["SqlServer"]);
            if (zhi > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }


        // 获取级联数据（I级→II级→III级）
        [HttpGet("GetCascadeData")]
        public async Task<IActionResult> GetCascadeData()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    "SELECT first_kind_id AS id, first_kind_name AS name FROM config_file_first_kind");

                // 构建级联数据结构
                var result = new List<dynamic>();

                foreach (var firstKind in firstKinds)
                {
                    // 查询对应的II级机构
                    var secondKinds = await connection.QueryAsync<dynamic>(
                        "SELECT second_kind_id AS id, second_kind_name AS name " +
                        "FROM config_file_second_kind " +
                        "WHERE first_kind_id = @Id",
                        new { Id = firstKind.id });

                    var secondList = new List<dynamic>();

                    foreach (var secondKind in secondKinds)
                    {
                        // 查询对应的III级机构
                        var thirdKinds = await connection.QueryAsync<dynamic>(
                            "SELECT third_kind_id AS id, third_kind_name AS name " +
                            "FROM config_file_third_kind " +
                            "WHERE second_kind_id = @Id",
                            new { Id = secondKind.id });

                        secondList.Add(new
                        {
                            id = secondKind.id,
                            name = secondKind.name,
                            children = thirdKinds
                        });
                    }

                    result.Add(new
                    {
                        id = firstKind.id,
                        name = firstKind.name,
                        children = secondList
                    });
                }

                return Ok(result);
            }
        }




        [HttpGet("GetSecondCascadeData")]
public async Task<IActionResult> GetSecondCascadeData(int? firstId = null)
{
    using (var connection = new SqlConnection(configuration["SqlServer"]))
    {
        await connection.OpenAsync();

        var query = @"
            SELECT 
                sk.second_kind_id AS id, 
                sk.second_kind_name AS name,
                ISNULL(
                    (SELECT 
                        tk.third_kind_id AS id, 
                        tk.third_kind_name AS name 
                     FROM config_file_third_kind tk 
                     WHERE tk.second_kind_id = sk.second_kind_id 
                     FOR JSON PATH), 
                    '[]') AS children -- 确保 children 不为 null，默认为空数组
            FROM config_file_second_kind sk 
            WHERE @firstId IS NULL OR sk.first_kind_id = @firstId
            GROUP BY sk.second_kind_id, sk.second_kind_name";

        var secondKinds = await connection.QueryAsync<dynamic>(query, new { firstId });
        
        
        return Ok(secondKinds);
    }
}


    }
}
